package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/jinzhu/gorm"
	"strconv"
	"time"
	"xw/models"
)

type XwController struct {
	beego.Controller
}

type ReturnMsg struct {
	Code string
	Msg  string
	Data interface{}
}

func (c *XwController) Add() {

	NewBh := c.GetString("NewBh")
	NewTitle := c.GetString("NewTitle")
	NewSort := c.GetString("NewSort")

	Xw := models.News{
		NewBh:    NewBh,
		NewTitle: NewTitle,
		NewSort:  NewSort,
	}
	get := models.Client.Get("Xw")
	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &Xw)

	} else {
		models.DB.Create(&Xw)
		Marshal, _ := json.Marshal(&Xw)
		models.Client.Set("Xw", Marshal, time.Minute*5)

	}

	c.Data["json"] = ReturnMsg{"200", "新闻添加成功", Xw}
	c.ServeJSON(true)

}
func (c *XwController) List() {

	var data []models.News

	id, _ := c.GetInt("id")
	get := models.Client.Get("list" + strconv.Itoa(id))

	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &data)
	} else {
		models.DB.Find(&data)
		Marshal, _ := json.Marshal(&data)
		models.Client.Set("loginErr", Marshal, time.Minute*3)
	}

	c.Data["json"] = ReturnMsg{"200", "新闻添加成功", data}
	c.ServeJSON(true)

}

func (c *XwController) Show() {

	id, _ := c.GetInt("id")

	Xw := models.News{
		Model: gorm.Model{ID: uint(id)},
	}

	models.DB.Where("id =?", id).Find(&Xw)
	c.Data["json"] = ReturnMsg{"200", "新闻展示成功", Xw}
	c.ServeJSON(true)

}

func (c *XwController) Del() {
	id, _ := c.GetInt("id")

	Xw := models.News{
		Model: gorm.Model{ID: uint(id)},
	}
	get := models.Client.Get("del" + strconv.Itoa(id))
	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &Xw)
	} else {
		models.DB.Where("id =?", id).Delete(&Xw)
		Marshal, _ := json.Marshal(&Xw)
		models.Client.Set("del", Marshal, time.Minute*3)
	}

	c.Data["json"] = ReturnMsg{"200", "新闻删除成功", Xw}
	c.ServeJSON(true)
}
func (c *XwController) Update() {

	NewBh := c.GetString("NewBh")
	NewTitle := c.GetString("NewTitle")
	NewSort := c.GetString("NewSort")
	id, _ := c.GetInt("id")

	Xw := models.News{
		Model:    gorm.Model{ID: uint(id)},
		NewBh:    NewBh,
		NewTitle: NewTitle,
		NewSort:  NewSort,
	}

	get := models.Client.Get("update" + strconv.Itoa(id))
	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &Xw)
	} else {
		models.DB.Debug().Model(&Xw).Where("ID = ?", id).Updates(&Xw)
		Marshal, _ := json.Marshal(&Xw)
		models.Client.Set("update", Marshal, time.Minute*5)
	}

	c.Data["json"] = ReturnMsg{"200", "修改成功", Xw}
	c.ServeJSON(true)

}
